package com.or.exercise.permutation;

import java.util.Arrays;

public class PermutationPrinter {

    public static void main(String... args) {

        String[] words = args.length == 0 ? 
                new String[] { "Hello", "World!" } : args;

        System.out.println("input: " + Arrays.toString(words));
        System.out.println("permutations: " + Arrays.toString(new PermutationPrinter().permutate(words)));
    }

    String[] permutate(String[] words, String[] permutations, int currentWord) {
        String[] prmts = new String[permutations.length * words[currentWord].length()];
        for (int i = 0, p = 0; i < permutations.length; i++)
            for (int j = 0; j < words[currentWord].length(); j++, p++)
                prmts[p] = permutations[i] + words[currentWord].charAt(j);

        return currentWord < words.length - 1 ? 
                permutate(words, prmts, ++currentWord) : prmts;
    }

    public String[] permutate(String[] words) {
        return permutate(words, new String[] { "" }, 0);
    }

}